
<?php
include('../conn.php');

$allowedExts = array("gif", "jpeg", "jpg", "png","xls");
$temp = explode(".", $_FILES["file"]["name"]);
echo 'FileType: '.$_FILES["file"]["type"];
$extension = end($temp);
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/x-png")
|| ($_FILES["file"]["type"] == "image/png")
|| ($_FILES["file"]["type"] == "application/vnd.ms-excel"))
&& ($_FILES["file"]["size"] < 300000)
&& in_array($extension, $allowedExts))
  {
  if ($_FILES["file"]["error"] > 0)
    {
    echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
    }
  else
    {
    echo "Upload: " . $_FILES["file"]["name"] . "<br>";
    echo "Type: " . $_FILES["file"]["type"] . "<br>";
    echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
    echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";

    if (file_exists("" . $_FILES["file"]["name"]))
      {
      //echo $_FILES["file"]["name"] . " already exists. ";
      }
    else
      {
      move_uploaded_file($_FILES["file"]["tmp_name"],
      "" . $_FILES["file"]["name"]);
      echo "Stored in: " . "" . $_FILES["file"]["name"];
      }
    }
  }
else
  {
  echo "Invalid file";
  }
?> 

<?php
// Test CVS

require_once 'Excel/reader.php';


// ExcelFile($filename, $encoding);
$data = new Spreadsheet_Excel_Reader();


// Set output Encoding.
$data->setOutputEncoding('CP1251');

/***
* if you want you can change 'iconv' to mb_convert_encoding:
* $data->setUTFEncoder('mb');
*
**/

/***
* By default rows & cols indeces start with 1
* For change initial index use:
* $data->setRowColOffset(0);
*
**/



/***
*  Some function for formatting output.
* $data->setDefaultFormat('%.2f');
* setDefaultFormat - set format for columns with unknown formatting
*
* $data->setColumnFormat(4, '%.3f');
* setColumnFormat - set format for column (apply only to number fields)
*
**/

$inputcsv = $_FILES["file"]["name"];

///###############################################Replace , in the file with EMPTY string
//open file and get data 
//$data = file_get_contents($inputcsv);
// do tag replacements or whatever you want
//$data = str_replace(",", "", $data);
//save it back:
//file_put_contents($inputcsv, $data);
////###############################################Replace , in the file with EMPTY string



$data->read($inputcsv);

/*


 $data->sheets[0]['numRows'] - count rows
 $data->sheets[0]['numCols'] - count columns
 $data->sheets[0]['cells'][$i][$j] - data from $i-row $j-column

 $data->sheets[0]['cellsInfo'][$i][$j] - extended info about cell
    
    $data->sheets[0]['cellsInfo'][$i][$j]['type'] = "date" | "number" | "unknown"
        if 'type' == "unknown" - use 'raw' value, because  cell contain value with format '0.00';
    $data->sheets[0]['cellsInfo'][$i][$j]['raw'] = value if cell without format 
    $data->sheets[0]['cellsInfo'][$i][$j]['colspan'] 
    $data->sheets[0]['cellsInfo'][$i][$j]['rowspan'] 
*/

error_reporting(E_ALL ^ E_NOTICE);

$startcell = 'Bkng Date';
$startrow = 0;
for ($i = 1; $i <= $data->sheets[0]['numRows']; $i++) {
	for ($j = 1; $j <= $data->sheets[0]['numCols']; $j++) {
		$celldata = trim($data->sheets[0]['cells'][$i][$j]);
		if($celldata == $startcell) {
			$startrow = $i;
			break;
			}
		else
			continue;
	}
	if($startrow!=0) break;
}

$outputcsv = 'invoice-'.date("Y-m-d-H-i-s").'.csv';

//echo 'startrow'.':'.$startrow.':';

$celldata = '';

if($startrow!=0){
	$file = fopen($outputcsv,"w");
	for ($i = $startrow; $i <= $data->sheets[0]['numRows']; $i++) {
			$celldata='';
			
	for ($j = 1; $j <= $data->sheets[0]['numCols']; $j++) {
			$c = trim($data->sheets[0]['cells'][$i][$j]);
			if($j==1) 
			{
				if(trim($c)=='') 
				{
					$i = $data->sheets[0]['numRows'];
					break;
				}
			}
			$celldata = $celldata.$c.',';
		}
		if($celldata!=''){
			$cells = explode(",", $celldata);
			if(($cells[2]!='N/A') && (($cells[21]=='shreecommuni@yahoo.co.in') || ($cells[21]=='Agent')))
			{
			echo fwrite($file,$celldata.',');
			echo fwrite($file,PHP_EOL);
			}
		}
	}
	
	fclose($file);
}



//include('conn.php');

if (($handle = fopen($outputcsv, "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $num = count($data);
        //echo "<p> $num fields in line $row: <br /></p>\n";
        $row++;
        for ($c=0; $c < $num; $c++) {
            //echo $data[$c] . "<br />\n";
        }
				
		$qry1 = 'insert into csvtable(`file`,`Bkng Date`,`YT Number` 	,	`PaxName` 	,	`Basic`	,	`Net Payable` ,		`Agent`	,	`entrydt`, 	`processed`) values(;'.$outputcsv.';,;'.$data[0].';,'.$data[1].',;'.$data[4].';,'.$data[10].','.$data[19].',;'.$data[21].';,CURDATE(),0)';
		 $qry1 = str_replace(";", "'", $qry1);
		//echo $qry1.'\r\n';
		$qry = mysql_query($qry1);
		//echo $qry;
    }
    fclose($handle);
}


echo '<h1>File uploaded successfully to csvtable</h1>'
//print_r($data);
//print_r($data->formatRecords);


?>


<?
// do stuff here
$url = 'processinvoicefile.php?invoicefile='.$outputcsv; // this can be set based on whatever

  echo "<script>window.location = ".$url."</script>";
  
  ?>

